<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,viewport-fit=cover">
    <link href="plugs/layui/css/layui.css" rel="stylesheet"/>
    <link href="common/css/index.css" rel="stylesheet"/>
    <link href="common/css/common.css" rel="stylesheet"/>
</head>
<body>
<div class="main">
    <div class="header" th:include="include :: header"></div>
    <div class="content">
        <div class="layui-container">
            <div class="layui-row">
<!--                <div class="layui-col-xs4 layui-col-sm5 layui-col-md4">-->
<!--                    <a href=""><img src="" /></a>-->
<!--                </div>-->
            </div>
        </div>
    </div>
    <div class="footer" th:include="include :: footer"></div>

    <div class="option">
        <a href="javascript:void(0);" onclick="createFolder();" class="option-add"><img src="/common/images/add.png" alt=""></a>
        <a href="javascript:void(0);" class="option-up"><img src="/common/images/up.png" alt="" onclick="$('#file').click()"><input type="file" id="file" accept="video/mp4,image/*"></a>
    </div>
</div>


<script src="common/js/jquery.min.js"></script>
<script src="plugs/layui/layui.js"></script>
<script src="common/js/common.js"></script>

<script>
    // 节流
    function throttle(fn, delay = 200) {
        let timer = null;
        return function () {
            if (timer) return;
            timer = setTimeout(() => {
                fn.apply(this, arguments);
                timer = null;
            }, delay);
        };
    }
    // 懒加载-回调函数
    function lazyLoad() {
        const imgs = document.querySelectorAll('img[data-src]');
        if (!imgs.length) return;
        imgs.forEach(img => {
            const rect = img.getBoundingClientRect();
            if (rect.top < window.innerHeight) {
                img.src = img.dataset.src;
                img.removeAttribute('data-src'); // 我们是通过img[data-src]查找所有img标签的，渲染后就删除data-src可减少forEach循环的计算成本
            }
        })
    }
    // 全局监听scroll滚动事件
    window.addEventListener('scroll', throttle(() => {lazyLoad();
    }, 100));
</script>

<script>
    // 基础路径
    var basePath = '';
    // 当前路径
    var currentPath = '';
    // 长按事件定时器
    var timeOutEvent;
    var page = 1;
    var pageSize = 15
    var totalPage = 1;

    // 初始加载内容
    loadFile('');

    /**
     * 返回按钮
     */
    function goBack() {
        // if (basePath !== ''){
            loadFile(basePath);
        // }else {
        //     window.history.go(-1);
        // }
    }

    /**
     * 获取文件列表
     * @param path
     */
    function loadFile(path) {
        $.ajax({
            url:'/api/getFiles',
            type:"get",
            data:{'path': path, 'page': page, 'pageSize': pageSize},
            dataType:'json',
            async: false,
            success:function(result){
                if (result.code === 200){
                    let content = '';
                    let data = result.data.fileInfoList;
                    basePath = result.data.parentPath;
                    currentPath = result.data.currentPath;
                    page = result.data.page;
                    pageSize = result.data.pageSize;
                    totalPage = result.data.totalPage;
                    for (let dataKey in data) {
                        content += '<div class="layui-col-xs4">\n';
                        if (data[dataKey].picture){
                            content+='                    <a href="javascript:void(0);" onclick="enlarge(\''+data[dataKey].photo+'\')">';
                        }else if(data[dataKey].folder){
                            content+='                    <a href="javascript:void(0);" onclick="loadFile(\''+data[dataKey].path+'/'+data[dataKey].fileName+'\')">';
                        }else {
                            content+='                    <a href="javascript:void(0);" onouchstart="gtouchstart();" ontouchend="gtouchend();" ontouchmove="gtouchmove();">';
                        }
                        content+='<p><img data-src="'+data[dataKey].photo+'" class="img-item" /></p><font>'+data[dataKey].fileName+'</font></a>\n' +
                            '                </div>'
                    }

                    $(".layui-row").append(content);
                    // 初始化的时候执行一下加载图片的函数
                    lazyLoad();
                }
            }
        });
    }

    /**
     * 放大
     */
    function enlarge(url) {
        layer.open({
            closeBtn: 0,
            title:'',
            btn:[],
            shadeClose: true,
            area: ['100%', '100%'],
            content: '<div class="open-div" onclick="layer.closeAll();"><img class="open-img" src="'+url+'"/></div>',
            success: function(layero, index) {
                // layer.iframeAuto(index);
            },
        })
    }

    /**
     * 开始按
     * @param id
     * @returns {boolean}
     */
    function gtouchstart(id) {
        timeOutEvent = setTimeout("alert(11);", 1000);
        return false;
    }

    /**
     * 手释放
     * @returns {boolean}
     */
    function gtouchend() {
        clearTimeout(timeOutEvent); //清除定时器
        if (timeOutEvent !== 0) {
            //这里写要执行的内容（尤如onclick事件）
            console.log("你这是点击，不是长按");
        }
        return false;
    }

    /**
     * 如果手指有移动，则取消所有事件，此时说明用户只是要移动而不是长按
     */
    function gtouchmove() {
        clearTimeout(timeOutEvent); //清除定时器
        timeOutEvent = 0;
    }

    /**
     * 创建文件夹
     */
    function createFolder() {
        layer.open({
            closeBtn: 1,
            title:'新建文件夹',
            btn:['保存', '关闭'],
            // area: ['100%', '30%'],
            btnAlign: 'c',
            content: '' +
                '<form class="layui-form">\n' +
                '  <div class="layui-form-item">\n' +
                // '    <label class="layui-form-label"><font color="red">*</font>文件夹名称</label>\n' +
                // '    <div class="layui-input-block">\n' +
                '      <input type="text" name="name" id="name" placeholder="请输入文件夹名称" autocomplete="off" class="layui-input">\n' +
                // '    </div>\n' +
                '  </div>' +
                '</form>',
            yes: function () {
                let name = $("#name").val();
                if (name === ''){
                    layer.msg('请输入文件夹名称', {icon: 2, time: 1000});
                    return false;
                }
                $.ajax({
                    url:'/api/createFolder',
                    data: {"name":name, 'path': currentPath},
                    type:"post",
                    dataType:'json',
                    success:function(result){
                        console.log(result);
                        if (result.code === 200){
                            // 设置cookie
                            layer.msg(result.msg, {icon:1, time:1000}, function () {
                                loadFile(basePath);
                            });
                        }else {
                            layer.msg(result.msg, {icon:2});
                        }
                    }
                });
            },
            btn2: function (index) {
                layer.close(index);
            }
        })
    }

</script>

<script>
    $(function () {
        $("#file").on("change", function () {
            let file = document.getElementById("file").files[0];
            let formData = new FormData();
            formData.append("file", file);
            formData.append("path", currentPath);
            $.ajax({
                type: 'post',
                url: "/api/uploadFile",
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
            }).success(function (result) {
                loadFile(currentPath);
            }).error(function () {
                layer.msg("头像修改失败", {icon: 2});
            });
        })
    })

</script>

<script type="text/javascript">
    var totalHeight = $(document).height();//整个文档高度
    var seeHeight = $(window).height();//浏览器可视窗口高度
    var thisBodyHeight = $(document.body).height();//浏览器当前窗口文档body的高度
    var totalBodyHeight = $(document.body).outerHeight(true);//浏览器当前窗口文档body的总高度 包括border padding margin
    var thisWidth = $(window).width(); //浏览器当前窗口可视区域宽度
    var thisDocumentWidth = $(document).width();//浏览器当前窗口文档对象宽度
    var thisBodyWidth = $(document.body).width();//浏览器当前窗口文档body的宽度
    var totalBodyWidth = $(document.body).outerWidth(true);//浏览器当前窗口文档body的总宽度 包括border padding margin
    var scrollTop = $(window).scrollTop();//浏览器可视窗口顶端距离网页顶端的高度（垂直偏移）
    // console.log(totalHeight,seeHeight,thisBodyHeight,totalBodyHeight,thisWidth,thisDocumentWidth,thisBodyWidth,totalBodyWidth,scrollTop);
    //添加滚动事件
    $(window).scroll(function(){
        scrollTop = $(window).scrollTop();
        totalHeight = $(document).height();
        // console.log(scrollTop,seeHeight,totalHeight)
        if(scrollTop+seeHeight+50>totalHeight){
            if (page<totalPage){
                page++;
                loadFile(currentPath);
            }else {
                console.log('到底了');
            }
        }
    })
</script>
</body>
</html>